package org.subject.controller;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.subject.dto.*;
import org.subject.entity.Message;
import org.subject.entity.Registration;
import org.subject.entity.User;
import org.subject.service.MessageService;
import org.subject.service.RegistrationService;
import org.subject.utils.DateUtil;
import org.subject.utils.ExcelUtil;
import org.subject.utils.ViewExcel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报名相关信息控制器
 * Created by kai on 2017/5/1.
 */
@Controller
@RequestMapping("/regist")
public class RegistrationController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RegistrationService registrationService;
    @Autowired
    private MessageService messageService;

    private String messageId;

    /**
     * 获取报名列表
     *
     * @param model
     * @param messageId
     * @return
     */
    @RequestMapping("/list")
    public String getRegisterList(Model model, @RequestParam("messageId") String messageId) {
        List<User> userList = registrationService.selectUserList(messageId);
        Message message = messageService.getById(Long.parseLong(messageId));
        model.addAttribute("userList", userList);
        model.addAttribute("message", message);
        return "registerList";
    }

    @RequestMapping("/listByFId")
    public String getRegisterListByFId(Model model, @RequestParam("messageId") String messageId,
                                       @RequestParam("facultyId") String facultyId,
                                       @RequestParam("type") String type) {
        List<User> userList;
        if (type.equals("1")) {
            userList = registrationService.selectUserListByFId(messageId, null);
        } else {
            userList = registrationService.selectUserListByFId(messageId, facultyId);
        }
        Message message = messageService.getById(Long.parseLong(messageId));
        model.addAttribute("userList", userList);
        model.addAttribute("message", message);
        return "registerList";
    }

    /**
     * 下载报名列表
     *
     * @param modelMap
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    public ModelAndView exportExcel(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        ViewExcel viewExcel = new ViewExcel();
        String messageId = request.getParameter("messageId");
        logger.info(messageId);
        Map<String, Object> obj = null;
        List<User> userList = registrationService.selectUserList(messageId);
        //获取数据库表生成的workbook
        HSSFWorkbook workbook = ExcelUtil.generateWorkbook(userList);
        try {
            viewExcel.buildExcelDocument(obj, workbook, request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ModelAndView(viewExcel, modelMap);
    }

    @RequestMapping(value = "/addregist", method = RequestMethod.GET)
    public String regist(Model model, @RequestParam("messageId") String messageId, @RequestParam("userId") String userId) {
        logger.error(messageId + "-->" + userId);
        int code = registrationService.insert(messageId, userId);
        logger.info("插入数据成功" + code);
        Long id = Long.parseLong(messageId);
        Registration registration = registrationService.selectByMIdUid(messageId, userId);
        MessageAndUser messageAndUser = messageService.selectMUByKey(id);
        logger.info(messageAndUser.toString());
        model.addAttribute("title", messageAndUser.getMessageTitle());
        model.addAttribute("content", messageAndUser.getMessageContent());
        model.addAttribute("desc", messageAndUser.getMessageDesc());
        model.addAttribute("registerstart", DateUtil.dateToStr(messageAndUser.getRegistrationStartTime()));
        model.addAttribute("registerend", DateUtil.dateToStr(messageAndUser.getRegistrationEndTime()));
        model.addAttribute("teststart", DateUtil.dateToStr(messageAndUser.getStartTime()));
        model.addAttribute("testend", DateUtil.dateToStr(messageAndUser.getEndTime()));
        model.addAttribute("requirement", messageAndUser.getContestRequirement());
        model.addAttribute("messageid", messageAndUser.getMessageId());
        model.addAttribute("createtime", messageAndUser.getCreateTime());
        model.addAttribute("name", messageAndUser.getUserName());
        model.addAttribute("userid", messageAndUser.getUserId());
        model.addAttribute("state", registration.getRegistrationState());
        return "detail";
    }

    /**
     * 获取报名列表
     *
     * @param model
     * @param messageId
     * @return
     */
    @RequestMapping("/cord")
    public String getCordRegisterList(Model model, @RequestParam("messageId") String messageId) {
        messageId = messageId;
        List<RegisteMessage> registeMessages = registrationService.selectRegisteMessage(messageId);
        for (RegisteMessage registeMessage : registeMessages) {
            logger.info(registeMessage.toString());
        }
        Message message = messageService.getById(Long.parseLong(messageId));
        model.addAttribute("registeMessages", registeMessages);
        model.addAttribute("message", message);
        return "handler";
    }

    /**
     * 设置竞赛相关信息
     *
     * @return
     */
    @RequestMapping(value = "/set", method = RequestMethod.POST)
    public String getCordResult(Model model, @RequestBody List<RegisterCord> registerCord) {
        /*if (registeMessageList != null) {
            for (RegisteMessage registeMessage : registeMessageList) {
                logger.info(registeMessage.toString());
            }
        }*/
        /*try {
            String str = URLDecoder.decode(request.getParameter("orderJson"),"UTF-8");
            logger.info("字符串："+str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        logger.info("数量：" + registerCord.size());
        if (registerCord != null) {
            for (RegisterCord cord : registerCord) {
                logger.info("cord:" + cord.toString());
                Registration registration = new Registration();
                registration.setRegistrationId(Long.valueOf(cord.getRegistrationId()));
                registration.setRegistrationSeat(cord.getSeat());
                registration.setRegistrationScore(cord.getGrade());
                int code = registrationService.updateByPrimaryKey(registration);
                logger.info("Code:" + code);
            }
        }
        List<RegisteMessage> registeMessages = registrationService.selectRegisteMessage(messageId);
        Message message = messageService.getById(Long.parseLong(messageId));
        model.addAttribute("registeMessages", registeMessages);
        model.addAttribute("message", message);
        return "handler";
    }

    /**
     * 用户竞赛历史
     *
     * @param model
     * @param userId
     * @return
     */
    @RequestMapping("/userhistory")
    public String getUserHistoryList(Model model, @RequestParam("userId") String userId) {
        List<RegisteUserMessage> registeUserMessages = registrationService.selectRegisteUserMessage(userId);
        model.addAttribute("registeUserMessages", registeUserMessages);
        return "alsocontest";
    }

    /**
     * 上传文件
     *
     * @param uploadFile
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upLoad", method = RequestMethod.POST)
    public String upLoad(Model model, MultipartFile uploadFile, @RequestParam("id") String id, HttpSession session) throws Exception {
        //获取文件名称作为保存到服务器的文件名称
        if (uploadFile.getSize() > 0) {
            String fileName = uploadFile.getOriginalFilename();
            Registration registration = registrationService.selectByPrimaryKey(id);
            registration.setRegistrationRemark(fileName);
            registrationService.updateByPrimaryKey(registration);
            //可以限制上传文件的类型
            //前半部分路径，目录，将WebRoot下一个名称为file文件夹转化成绝对路径
//            String path = session.getServletContext().getRealPath("/resource");
            String path = "E:upload";
            //进行路径拼接
            File file = new File(path, fileName);
            uploadFile.transferTo(file);
        }
        User user = (User) session.getAttribute("user");
        List<RegisteUserMessage> registeUserMessages = registrationService.selectRegisteUserMessage(String.valueOf(user.getUserId()));
        model.addAttribute("registeUserMessages", registeUserMessages);
        return "alsocontest";
    }

    @RequestMapping("/dowload")
    public ResponseEntity<byte[]> dowload(@RequestParam("address") String address, HttpSession session) throws IOException {
        String path = "E:upload";
        File file = new File(path + "/" + address);
        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(address.getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    @RequestMapping("/contestHistory")
    public String contestHistory(Model model, @RequestParam("userId") String userId) {
        List<RegisteUserMessage> registeUserMessages = registrationService.selectRegisteUserMessage(userId);
        List<RegisteUserMessage> userMessages = new ArrayList<RegisteUserMessage>();
        for (RegisteUserMessage registeUserMessage : registeUserMessages) {
            if (DateUtil.compare(registeUserMessage.getEndTime(), new Date())) {
                userMessages.add(registeUserMessage);
            }
        }
        model.addAttribute("registeUserMessages", userMessages);
        return "contestHistory";
    }
}
